﻿using System;
using System.Collections.Generic;
using System.Threading;

namespace MyDemo.Lazy
{
    public class LazyDemo
    {
        /// <summary>
        /// Lazy<T>延时加载示例代码
        /// http://www.cnblogs.com/wpfworld/p/3181014.html
        /// </summary>
        public static void Test()
        {
            //
            foreach (var item in Product.GetProductListLazy())
            {
                //下面的操作会执行Product类的构造函数
                Product p = item.Value;
                //构造函数执行完成
                int id = item.Value.Id;
                Console.WriteLine(id);
            }

            //
            //foreach (var item in Product.GetProductList())
            //{
            //    int id = item.Id;
            //    Console.WriteLine(id);
            //}
        }

        private class Product
        {
            public int Id { set; get; }
            public string Title { set; get; }

            public Product()
            {
                Thread.Sleep(1000);
            }

            /// <summary>
            /// 非延时
            /// </summary>
            /// <returns></returns>
            public static IList<Product> GetProductList()
            {
                try
                {
                    Console.WriteLine("非LazyLoad加载");
                    Console.WriteLine(DateTime.Now.ToString("HH:mm:ss.fff"));
                    Product product1 = new Product() { Id = 1, Title = "产品 1" };
                    Product product2 = new Product() { Id = 2, Title = "产品 2" };
                    Product product3 = new Product() { Id = 3, Title = "产品 3" };
                    return new List<Product> { product1, product2, product3 };
                }
                finally
                {
                    Console.WriteLine(DateTime.Now.ToString("HH:mm.ss.fff"));
                }
            }

            /// <summary>
            /// 延时
            /// </summary>
            /// <returns></returns>
            public static IList<Lazy<Product>> GetProductListLazy()
            {
                try
                {
                    Console.WriteLine("非LazyLoad加载");
                    Console.WriteLine(DateTime.Now.ToString("HH:mm:ss.fff"));
                    Lazy<Product> product1 = new Lazy<Product>(() => new Product { Id = 1, Title = "产品 1" });
                    Lazy<Product> product2 = new Lazy<Product>(() => new Product { Id = 2, Title = "产品 2" });
                    Lazy<Product> product3 = new Lazy<Product>(() => new Product { Id = 3, Title = "产品 3" });
                    Lazy<Product> product4 = new Lazy<Product>(() => new Product { Id = 4, Title = "产品 4" });
                    return new List<Lazy<Product>> { product1, product2, product3 };
                }
                finally
                {
                    Console.WriteLine(DateTime.Now.ToString("HH:mm.ss.fff"));
                }
            }

     
        }
    }
}